# -*- encoding : utf-8 -*-
#-------------------------------------
# Tu
#-------------------------------------
class Default::BookController < ApplicationController
  # specific layout
  layout 'default/application'
  
  # list new books
  def index
    if params[:cate]
      @new_books = Book.where("book_category_id = ?", params[:cate]).order('created_at desc')
    else
      @new_books = Book.order('created_at desc')
    end
    if !params[:all] or params[:all] == 'false'
      @new_books = @new_books.limit(5) # why not work with paginating
    end

    @new_books = @new_books.paginate(:page => params[:page], :per_page => 5)
    
    @featured_books = []
    all_cates = BookCategory.all
    all_cates.each do |cate|
      fb = Book.where('book_category_id = ?', cate.id).order('created_at desc').first
      last = @featured_books.length
      @featured_books[last] = fb
    end
  end
  
  # view the information of a book
  def view
    @book = Book.find(params[:id])
  end
  
  # search a book
  def search
    @keyword = params[:keyword]
    cate = params[:cate]
    
    if params[:search]  # check if button search is clicked
      if params[:keyword] != ''
        case(cate.to_i)
         when 0 then # title
           @results_list = Book.where("title LIKE ?", "%#{@keyword}%")
         when 1 then # author
           @results_list = Book.where("author LIKE ?", "%#{@keyword}%")
         when 2 then # category
           @results_list = Book.where(book_category_id: BookCategory.where("category_name LIKE ?", "%#{@keyword}%"))
         when 3 then # publisher
           @results_list = Book.where("publisher LIKE ?", "%#{@keyword}%") 
        end
        @results_list = @results_list.paginate(:page => params[:page], :per_page => 5)
        flash[:notice] = nil
      else
        flash[:notice] = "Please enter keyword"  
      end
    end # end if
  end
  
  # reserve borrowing a book
  def reserve
    @book_reserve = BookReserve.new(
      :user_id => session[:user_id],
      :book_id => params[:id],
    )
    @book = Book.find(params[:id])
    if @book_reserve.save
      flash[:notice] = "You have reserved this book successfully. We will send email notice to you when the book you reserved is available"
    else
      flash[:notice] = "There are some errors"
    end
  end
  
end
